iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 27
0
自我挑戰組

Leetcode新手挑戰30天系列 第 27

#804 Unique Morse Code Words

  • 分享至 

  • xImage
  •  

寫在開頭

今天選的這題一樣是選#Easy、答對率也高的題目

進入正題

題目內容:

International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on.
For convenience, the full table for the 26 letters of the English alphabet is given below:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, "cba" can be written as "-.-..--...", (which is the concatenation "-.-." + "-..." + ".-"). We'll call such a concatenation, the transformation of a word.
Return the number of different transformations among all words we have.
Example:
Input: words = ["gin", "zen", "gig", "msg"]
Output: 2
Explanation:
The transformation of each word is:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."
There are 2 different transformations, "--...-." and "--...--.".

我想到的做法是先用replace()函式把每個英文字母都取代成對應的摩斯代碼,在用set()留下不同的字串
所以想到的程式碼架構大概長這樣:

    def uniqueMorseRepresentations(self, words: List[str]) -> int:
        morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        new_words = []
        for i in words:
            for j in i:
                i = i.replace(j,morse[ord(j)-97])
            new_words.append(i)
        return len(set(new_words))

這邊有查到參考1用ord的方式可以找出字母的ASCII十進位值,因為a~z是97~122,是連續的一串,所以拿到ASCII之後減去開頭的97就好。
submit後結果如下:
https://ithelp.ithome.com.tw/upload/images/20190929/20113393yG2yqNZEYm.png

參考資料

參考1在Python中将字母字母转换为数字


上一篇
#1108 Defanging an IP Address
下一篇
#1185 Day of the Week
系列文
Leetcode新手挑戰30天31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言